package com.leemon.mall.common.xss;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * @author limenglong
 * @create 2019-09-05 18:36
 * @desc Xss攻击过滤
 **/
public class XssWrapper extends HttpServletRequestWrapper {

    //是否包含富文本
    private boolean isIncludeRichText;
    //原始的request请求
    private HttpServletRequest orgRequest;

    /**
     * Constructs a request object wrapping the given request.
     *
     * @param request The request to wrap
     * @throws IllegalArgumentException if the request is null
     */
    public XssWrapper(HttpServletRequest request, boolean isIncludeRichText) {
        super(request);
        orgRequest = request;
        this.isIncludeRichText = isIncludeRichText;

    }

    /**
     * 对参数进行特殊字符过滤
     *
     * @param name
     * @return
     */
    @Override
    public String getParameter(String name) {
        boolean flag = ("content".equals(name)) || name.endsWith("WithHtml");
        if (flag && !isIncludeRichText) {
            return super.getParameter(name);
        }

        name = XssUtil.clean(name);
        String value = super.getParameter(name);
        if (StringUtils.isNotBlank(value)) {
            value = XssUtil.clean(value);
        }
        return value;
    }

    /**
     * 对数组参数进行特殊字符过滤
     *
     * @param name
     * @return
     */
    @Override
    public String[] getParameterValues(String name) {
        String[] arr = super.getParameterValues(name);
        if (ArrayUtils.isNotEmpty(arr)) {
            for (int i = 0; i < arr.length; i++) {
                arr[i] = XssUtil.clean(arr[i]);
            }
        }
        return arr;
    }

    /**
     * 对请求头进行特殊字符过滤
     *
     * @param name
     * @return
     */
    @Override
    public String getHeader(String name) {
        name = XssUtil.clean(name);
        String value = super.getHeader(name);
        if (StringUtils.isNotBlank(value)) {
            value = XssUtil.clean(value);
        }
        return value;
    }

    /**
     * 获取attribute，进行特殊字符过滤
     *
     * @param name
     * @return
     */
    @Override
    public Object getAttribute(String name) {
        Object value = super.getAttribute(name);
        if (value instanceof String && StringUtils.isNotBlank((String) value)) {
            return XssUtil.clean((String) value);
        }
        return value;
    }

    /**
     * 获取最原始的request
     *
     * @return
     */
    public HttpServletRequest getOrgRequest() {
        return orgRequest;
    }
}
